package com.kuaimacode.kframework.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kuaimacode.kframework.enums.AppletsPushTemplateEnum;
import com.kuaimacode.kframework.mybatis.models.user.User;
import com.kuaimacode.kframework.service.WeixinTokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * @author qinyong
 * @Title:
 * @Package com.kuaimacode.kframework.component
 * @Description: created by IntelliJ IDEA
 * @date 2019-07-18 09:01
 */
@Slf4j
@Component
public class AppletsPushService {

    @Value("${weixin.order.push.template}")
    private String orderTemplateId;
    @Autowired
    private BaseMapper<User> userBaseMapper;
    @Autowired
    private WeixinTokenService weixinTokenService;

    private static final String PUSH_URL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s";

    @Async
    public void pushMessage(Long userId, String templateId, String page, String formId, Object data) {
        log.info("push applets message, userId: {}, templateId: {}, page: {}, formId: {}, data: {}", userId, templateId, page, formId, JSON.toJSONString(data));
        User user = userBaseMapper.selectById(userId);
        if (StringUtils.isBlank(user.getOpenId())) {
            return;
        }
        String token;
        try {
            token = weixinTokenService.getToken();
        } catch (Exception e) {
            log.error("push error because get token error", e);
            return;
        }
        String url = String.format(PUSH_URL, token);
        Map<String, Object> params = new HashMap<>();
        params.put("touser", user.getOpenId());
        params.put("template_id", templateId);
        params.put("page", page);
        params.put("form_id", formId);
        params.put("data", data);
        try {
            for (int i = 0; i < 10; i++) {
                String response = doPost(url, JSONObject.toJSONString(params));
                log.info("push applets message result: {}", response);
                if (JSONObject.parseObject(response).getIntValue("errcode") == 0) {
                    break;
                }
            }
        } catch (Exception e) {
            log.error("push applets message error, userId: [{}], templateId: [{}], data: {}", userId, templateId, JSONObject.toJSON(data), e);
        }
    }

    @Async
    public void pushMessage(Long userId, Object data, String formId, AppletsPushTemplateEnum templateEnum) {
        pushMessage(userId, templateEnum.getTemplateId(), templateEnum.getPage(), formId, data);
    }

    public static String doPost(String url, String json) {
        String returnValue = "这是默认返回值，接口调用失败";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try{
            //第一步：创建HttpClient对象
            httpClient = HttpClients.createDefault();

            //第二步：创建httpPost对象
            HttpPost httpPost = new HttpPost(url);

            //第三步：给httpPost设置JSON格式的参数
            StringEntity requestEntity = new StringEntity(json,"utf-8");
            requestEntity.setContentEncoding("UTF-8");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(requestEntity);

            //第四步：发送HttpPost请求，获取返回值
            returnValue = httpClient.execute(httpPost,responseHandler); //调接口获取返回值时，必须用此方法

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //第五步：处理返回值
        return returnValue;
    }
}
